package com.bs.visitservice.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;



/**
 * 用来生成和校验jwt
 */
public class JwtUtil {
    public static void main(String[] args){
      /*  Calendar c = Calendar.getInstance();
        c.add(Calendar.DAY_OF_MONTH,1);
       String token =  genToken(null,c.getTime());
       System.out.println(token);*/
      verifyToken("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1ODE4MzY1MDR9.yGrdLtWV1Imd3g3iC_sofjK2OW-eVaAU9QE8r0yOGqo");
    }
    private static final String SECRET = "123456789";
    public static String genToken(Map<String, Object> claims, Date expireDatePoint){

        try {
            //使用HMAC256进行加密
            Algorithm algorithm = Algorithm.HMAC256(SECRET);  //密钥

            //创建jwt
            JWTCreator.Builder builder = JWT.create().
            withExpiresAt(expireDatePoint); //过期时间点

            //传入参数
            if(claims!=null){
                claims.forEach((key,value)-> {
                    if(value instanceof Long){
                        builder.withClaim(key, (Long)value);
                    }
                    if(value instanceof String){
                        builder.withClaim(key,(String)value);
                    }
                });
            }

            //签名加密
            return builder.sign(algorithm);
        } catch (IllegalArgumentException e) {
            throw new RuntimeException(e);
        }
    }
    public static Map<String,Object> verifyToken(String token) throws RuntimeException{
        Algorithm algorithm = null;
        try {
            //使用HMAC256进行加密
            algorithm = Algorithm.HMAC256(SECRET);
        } catch (IllegalArgumentException  e) {
            throw new RuntimeException(e);
        }

        //解密
        JWTVerifier verifier = JWT.require(algorithm).build();
        DecodedJWT jwt =  verifier.verify(token);
        Map<String, Claim> map = jwt.getClaims();
        Map<String, Object> resultMap = new HashMap<>();
        map.forEach((k,v) -> resultMap.put(k, v));
        return resultMap;
    }
}
